package ocean

import (
	"cid-media-api/api/common"
	"cid-media-api/global"
	"context"
	"github.com/go-redis/redis_rate/v10"
	oceanGo "github.com/oceanengine/ad_open_sdk_go"
	oceanApiConf "github.com/oceanengine/ad_open_sdk_go/config"
	"log"
	"net/http"
	"time"
)

const MediaIdOcean = 1
const MediaIdOceanQC = 10
const Page = 1
const PageSize = 100

var Api *oceanGo.Client

func SetUp() {
	configuration := oceanApiConf.NewConfiguration()
	configuration.UseLogMw = false // 关闭日志中间件
	Api = oceanGo.Init(configuration)
	Api.SetLogEnable(true)
}

func Call(fn func() (any, *http.Response, error), rlConfig common.RateLimitConfig) (any, *http.Response) {
	ctx := context.Background()
	res, err := global.RateLimiter.Allow(ctx, rlConfig.Key, redis_rate.PerSecond(rlConfig.Qps))

	if err == nil {
		for res.RetryAfter > 0 {
			time.Sleep(res.RetryAfter)
			res, err = global.RateLimiter.Allow(ctx, rlConfig.Key, redis_rate.PerSecond(rlConfig.Qps))
		}
	}

	if err != nil {
		log.Printf("接口请求次数过多, 接口: %v qps: %v", rlConfig.Key, rlConfig.Qps)
	}

	result, resp, err := fn()
	if err != nil {
		log.Printf("Failed to build up request, got error: %v", err)
		return nil, nil
	}

	return result, resp
}
